// Package avatar -----------------------------
// @file      : AvatarResourcesModel.go
// @author    : WuZhouHai
// @contact   : wzh200x@126.com
// @time      : 2024/7/4 15:56
// @desc      : 角色资源模块数据模型
// -------------------------------------------
package avatar

import (
	"github.com/gogf/gf/v2/util/gmeta"
	"phoenix/phoenix/common/logger"
	"phoenix/phoenix/defines/dataType"
	"phoenix/phoenix/entitys/entityModel"
	"phoenix/phoenix/interfaces"
	"phoenix/phoenix/managers/databaseManager"
	"phoenix/phoenix/utils"
)

type AvatarResourcesModelData struct {
	gmeta.Meta   `orm:"table: module_resource"`
	Dbid         dataType.PhoenixTypeDataBaseId `orm:"id"`
	AvatarId     dataType.PhoenixTypeDataBaseId `orm:"ownerId"`
	UpdateTime   string                         `orm:"update_time"`
	Carrot       int32                          `orm:"carrot"`
	Clover       int32                          `orm:"clover"`
	GoldCarrot   int32                          `orm:"gold_carrot"`
	Star         int32                          `orm:"star"`
	Score        int32                          `orm:"score"`
	MinuteCarrot int32                          `orm:"minute_carrot"`
	LastHarvest  int32                          `orm:"last_harvest"`
}

func NewAvatarResourcesModelData() *AvatarResourcesModelData {
	return &AvatarResourcesModelData{}
}

type AvatarResourcesModel struct {
	entityModel.ModuleSingleModel
}

func (this *AvatarResourcesModel) LoadModule() error {
	var records *AvatarResourcesModelData
	err := this.LoadModuleFromDB(&records)
	if err != nil {
		return err
	}

	if records == nil {
		err := this.Create()
		if err != nil {
			return err
		}
	} else {
		this.SetModelData(records.Dbid, records)
		this.SetModuleSingleDataDBID(records.Dbid)
	}

	return nil
}

func (this *AvatarResourcesModel) Create() error {
	base, err := databaseManager.PhoenixManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	data := NewAvatarResourcesModelData()
	data.AvatarId = this.EntityDBID
	data.UpdateTime = utils.GetNowTimeFormat()
	data.Carrot = 100
	data.Clover = 0
	data.GoldCarrot = 0
	dataDBid, err := base.GetDb().Model(this.Template).Data(data).OmitEmpty().InsertAndGetId()
	if err != nil {
		return err
	}
	data.Dbid = dataType.PhoenixTypeDataBaseId(dataDBid)
	this.SetModelData(data.Dbid, data)
	this.SetModuleSingleDataDBID(data.Dbid)
	logger.PhoenixLoggerIns().Debug("create AvatarResourcesModel success")
	return nil
}

func NewAvatarResourcesModel(name string, entityDBID dataType.PhoenixTypeDataBaseId) interfaces.IEntityModuleModel {
	m := &AvatarResourcesModel{
		ModuleSingleModel: entityModel.NewModuleSingleModel(name, entityDBID),
	}
	m.SetTemplate(NewAvatarResourcesModelData())
	return m
}
